package com.wpi.smarttour;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.wpi.smarttour.helpers.LocationListenerHelper;
import com.wpi.smarttour.helpers.SmartTourDBAdapter;
import com.wpi.smarttour.helpers.Utilities;

public class MapActivity extends Activity implements OnGestureListener
{
	
	// Static Map Vars
	private static final int X_MAX = 1441;           //X, Y size of map image (in pixels)
	private static final int Y_MAX = 1077;
	private static int X_RES = 320;
	private static int Y_RES = 480 - 50;             //-50 to account for Title Bar of App
	private static double LATITUDE_MAX = 52.68152;
	private static double LATITUDE_MIN = 52.66511;
	private static double LONGITUDE_MAX = -8.55074;
	private static double LONGITUDE_MIN = -8.58699;
	private static double LATITUDE_RES = (LATITUDE_MAX - LATITUDE_MIN)/Y_MAX;
	private static double LONGITUDE_RES = (LONGITUDE_MAX - LONGITUDE_MIN)/X_MAX;
	
	// Option Menu Variables
	static final private int MENU_MAP_VIEW = Menu.FIRST;
	static final private int MENU_SELECT_VIEW = Menu.FIRST + 1;
	static final private int MENU_BUILDING_VIEW = Menu.FIRST + 2;
	static final private int MENU_CLEAR_SELECTION = Menu.FIRST + 3;
	static final private int MENU_MAIN_MENU = Menu.FIRST + 4;
	static final private int MENU_EXIT = Menu.FIRST + 5;
	
	// Map Vars
	private int scrollX = 0;
	private int scrollY = 0;
	private long touchDownTime;
	private int counter = 0;
	private int[][] building_coords;
	private String[] building_names;
	private int currentX = -100;
	private int currentY = -100;
	private int buildingSelected;
	private int buildingX;
	private int buildingY;
	private String currentBuildingName = "";
	private boolean mapView = true;
	private boolean currentLocationSelectionView = false;
	private boolean buildingLocationSelectionView = false;
	MyView main;
	Bitmap map;
	Bitmap building_overlay;
	Bitmap adapt;
	Bitmap person;
	Bitmap bubble;
	Resources res;
	Paint paint;
	GestureDetector gestureScanner;
	
	// GPS
	LocationListenerHelper locationListener;
	LocationManager locationManager;
	// Finder
	PathFinder finder;
	
	// Locational Variables -- lower the seconds the more GPS readings
	private int minimumSeconds = 10;
	private int minimumDistance = 0;
	
	// Video Playing
	public static String FILE_NAME_FOR_PLAYBACK = "";

	// Select Mode
	String firstBuildingSection = "";
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		gestureScanner = new GestureDetector(this);
		paint = new Paint();
		res = getResources();
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPurgeable = true;
		map =  BitmapFactory.decodeResource(res, R.drawable.map, opt);
		building_overlay =  BitmapFactory.decodeResource(res, R.drawable.map_outlines, opt);
		person =  BitmapFactory.decodeResource(res, R.drawable.person, opt);
		bubble =  BitmapFactory.decodeResource(res, R.drawable.bubble2, opt);
		//building_overlay = building_overlay.copy(Bitmap.Config.ARGB_4444, true);
		adapt = Bitmap.createBitmap(map);
		main = new MyView(this);
		readBuildingsFromCSV();
		setContentView(main,new ViewGroup.LayoutParams(X_MAX,Y_MAX));
		
		// Set title of Activity
		setTitle("University of Limerick");

		//Location
		startGPS();
		
		// Grid + Finder
		finder = new PathFinder();
	}
	// When it comes back to this activity
	public void onResume()
	{
		Utilities.LogDebug("onResume - MapActivity");

		super.onResume();
		startGPS();
	}

	public void onStop()
	{
		Utilities.LogDebug("onStop - MapActivity");
		stopLocationMonitoring();
		super.onStop();

	}
	
	// Menu Creators
	public boolean onCreateOptionsMenu(Menu menu)
	{
		super.onCreateOptionsMenu(menu);
		
		// Create and add new menu items
		// Map Functions
		MenuItem itemMap = menu.add(0,MENU_MAP_VIEW,Menu.NONE,"Map View");
		MenuItem itemSelect = menu.add(0,MENU_SELECT_VIEW,Menu.NONE,"Select View");
		MenuItem itemBuilding = menu.add(3,MENU_BUILDING_VIEW,Menu.NONE, "Select Two Buildings");
		
		
		//Main Menu and Exit
		MenuItem itemClear = menu.add(3,MENU_CLEAR_SELECTION,Menu.NONE,"Clear Selection");
		MenuItem itemMainMenu = menu.add(1,MENU_MAIN_MENU,Menu.NONE,"Main Screen");
		MenuItem itemExit = menu.add(1,MENU_EXIT,Menu.NONE,"Exit");
	
		// icons
		itemMap.setIcon(R.drawable.menu_map_view);
		itemSelect.setIcon(R.drawable.menu_select_view);
		itemMainMenu.setIcon(R.drawable.menu_main_menu);
		itemExit.setIcon(R.drawable.menu_exit);
		
		return true;
	}

	
	// Menu Click 
	public boolean onOptionsItemSelected(MenuItem item)
	{
		super.onOptionsItemSelected(item);

		switch (item.getItemId())
		{
			case (MENU_MAP_VIEW):
			{
				Utilities.LogDebug("MapActivity: Map View Selected");
				mapView = true;
				currentLocationSelectionView = false;
				buildingLocationSelectionView = false;
				Utilities.msgUserShort("Map View", getApplicationContext());
				return true;
			}
			case (MENU_SELECT_VIEW):
			{
				Utilities.LogDebug("MapActivity: Select View Selected");
				mapView = false;
				currentLocationSelectionView = true;
				buildingLocationSelectionView = false;
				Utilities.msgUserShort("Select View", getApplicationContext());
				return true;
			}
			case (MENU_MAIN_MENU):
			{
				mapView = true;
				// Go back and stop GPS
				goBackToMainMenu();
				stopLocationMonitoring();
				return true;
			}
			case (MENU_EXIT):
			{
				stopLocationMonitoring();
				moveTaskToBack(true);
				//testing();
				return true;
			}
			case (MENU_BUILDING_VIEW):
			{
				mapView = false;
				currentLocationSelectionView = false;
				buildingLocationSelectionView = true;
				Utilities.msgUserShort("Please Select 2 Buildings", getApplicationContext());
				return true;
			}
			case (MENU_CLEAR_SELECTION):
			{
				Utilities.msgUserShort("Building Selection Cleared", getApplicationContext());
				firstBuildingSection = "";
				return true;
			}
			
	
		}
		return false;
	}
	
	private void goBackToMainMenu()
	{
		// can add more if needed
		
		finish();
	}
	
	
	// Gets called from the GPS Listener
	public void updateWithNewLocation(Location location)
	{
		//Utilities.msgUser("Updating Location - MapActivity", getApplicationContext());
		Utilities.LogDebug("Location: " + location.getLatitude() + " - " + location.getLongitude());

		int[] temp = locationToXY(location);
		currentX = temp[0];
		currentY = temp[1];
		setTitle(currentX + ", " + currentY);
		main.redraw();
	}

	// This checks the orentation of the phone
	// It make changes depending on this
	@Override
	public void onConfigurationChanged(Configuration newConfig)
	{
		super.onConfigurationChanged(newConfig);
		// Switch X and Y
		int temp = X_RES;
		if(X_RES < Y_RES)
		{
			X_RES = Y_RES + 50;
			Y_RES = temp - 50;
		}
		else
		{
			X_RES = Y_RES + 50;
			Y_RES = temp - 50;
		}
		main.redraw();
	}

	// Map Scrolling
	public boolean onTouchEvent(MotionEvent event)
	{
		int action = event.getAction();
		switch(action)
		{
		case MotionEvent.ACTION_DOWN:
			touchDownTime = SystemClock.elapsedRealtime();
			break;
		case MotionEvent.ACTION_UP:
			if(SystemClock.elapsedRealtime() - touchDownTime <= 300)
			{
				int x = (int)event.getX(); //or event.getRawX();
				int y = (int)event.getY();
				processForClick(x,y);
			}
			break;
		}
		return gestureScanner.onTouchEvent(event);
	}

	//User is scrolling the map
	//@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
	{
		main.handleScroll(distanceX,distanceY);
		return true;
	}

	//@Override
	public boolean onDown(MotionEvent e)
	{
		return true;
	}

	//@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
	{
		return true;
	}

	//@Override
	public void onLongPress(MotionEvent e)
	{
	}

	//@Override
	public void onShowPress(MotionEvent e)
	{
	}

	// @Override
	public boolean onSingleTapUp(MotionEvent e)
	{
		return true;
	}

	// Called when the user pressed down on the map
	public void processForClick(int x, int y)
	{
		// check what the user can see
		int[] temp = checkBounds(x + scrollX, y + scrollY - 48, X_MAX, Y_MAX);
		int x2 = temp[0];
		int y2 = temp[1];
		
		int color = building_overlay.getPixel(x2, y2);
		
		int red = Color.red(color);
		int green = Color.green(color);
		int blue = Color.blue(color);
		
		// check if the user clicked on a building
		if(blue == 0 && red > 235 && green > 235)
		{
			// Find the building that is clicked
			buildingSelected = processBuildingSelection(x2, y2);
			
			currentBuildingName = building_names[buildingSelected];
			buildingX = building_coords[buildingSelected][0];
			buildingY = building_coords[buildingSelected][1];

			// If not in Map View call video tour
			if (!mapView)
				processSelectionClick();
				

		}
		else // if not clicked on building
		{
			buildingSelected = -1;
			buildingX = -150;
			buildingY = -150;
		}
		
		main.redraw();
	}
	
	// This function is used for Video Tour where it finds the closest building
	public String queryForBuilding(int x, int y)
	{
		int x2 = x;
		int y2 = y;
		int tempCordsBuildingName;
		String tempCordsBuildingSelected;
		
		int color = building_overlay.getPixel(x2, y2);
	
		int red = Color.red(color);
		int green = Color.green(color);
		int blue = Color.blue(color);
		
		Utilities.LogDebug("MayActivity-queryForBuilding", "@ coords: " + (x2) + ", " + (y2) + ", Color = " + red + ", " + green + ", " + blue);
		// Check for yellow + purple
		if((blue == 0 && red > 235 && green > 235) || (red > 200 && green < 75 && blue > 150))
		{
			// find building
			Utilities.LogDebug("MayActivity-queryForBuilding", "Cords in yellow or purple zone");
			tempCordsBuildingName = processBuildingSelection(x2, y2);
			tempCordsBuildingSelected = building_names[tempCordsBuildingName];
			Utilities.LogDebug("MayActivity-queryForBuilding", "Video ended near this building ---" + tempCordsBuildingSelected);
			return tempCordsBuildingSelected;
		}
		else
		{
			Utilities.LogDebug("MayActivity-queryForBuilding", "Cords not in right zone");
			return null;
		}
	}

	// checks the bound of the screen
	public int[] checkBounds(int coord_x, int coord_y, int x_bound, int y_bound)
	{
		if(coord_x >= x_bound)
		{
			coord_x = x_bound - 1;
		}
		else if(coord_x < 0)
		{
			coord_x = 0;
		}
		if(coord_y >= y_bound)
		{
			coord_y = y_bound - 1;
		}
		else if(coord_y < 0)
		{
			coord_y = 0;
		}
		int values[] = {coord_x, coord_y};
		return values;
	}

	// Gets values from the CSV
	public void readBuildingsFromCSV()
	{
		try
		{
			building_coords = new int[25][2];
			building_names = new String[25];
			
			InputStream input = res.openRawResource(R.drawable.buildings);
			BufferedReader br = new BufferedReader(new InputStreamReader(input));
			StringTokenizer st = null;
			String inputLine = "";
			int line = 0;
			
			// Gather Data
			while((inputLine = br.readLine()) != null)
			{
				st = new StringTokenizer(inputLine, ",");
				building_coords[line][0] = Integer.parseInt(st.nextToken());
				building_coords[line][1] = Integer.parseInt(st.nextToken());
				building_names[line] = st.nextToken();
				line++;
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();			
		}
	}
	
	// Find building from X Y coords
	public int processBuildingSelection(int x, int y)
	{
		double distance_old = 1000;
		double distance_new = 0;
		int distX, distY, closest = 0;
		
		// Check all buildings
		for(int i=0;i<building_names.length;i++)
		{
			distX = (Math.abs(x-building_coords[i][0]));
			distX = distX * distX;
			distY = (Math.abs(y-building_coords[i][1]));
			distY = distY * distY;

			distance_new = Math.sqrt(distX + distY);
			if(distance_new < distance_old)
			{
				closest = i;
				distance_old = distance_new;
			}
			//setTitle(""+i);
		}
		return closest;
	}
	
	// Change GPS cords to XY
	public int[] locationToXY(Location gps_return)
	{
		return GPSToXY(gps_return.getLatitude(), gps_return.getLongitude());
	}    

	// Change XY to GPS cords
	public static double[] xyToGPS(int x, int y)
	{
		double[] coords= new double[2];
		coords[0] = LONGITUDE_MIN + LONGITUDE_RES*x;
		coords[1] = LATITUDE_MIN + LATITUDE_RES*y;
		return coords;
	}

	// Change lat and long to XY 
	public static int[] GPSToXY(double latitude, double longitude)
	{
		int[] coords= new int[2];
		
		// Using the resolution of the map
		coords[0] = (int)((longitude - LONGITUDE_MIN)/LONGITUDE_RES);
		coords[1] = (int)((LATITUDE_MAX - latitude)/LATITUDE_RES);
		
		return coords;
	}

	
	// Using LocationListenerHelper
	// Start GPS
	private void startGPS()
	{
		//Location
		String context = Context.LOCATION_SERVICE;
		locationManager = (LocationManager)getSystemService(context);

		// Criteria for what Location thing to use
		// Android picks the best choice 
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(false);
		criteria.setPowerRequirement(Criteria.POWER_HIGH);
		String provider = locationManager.getBestProvider(criteria, true);

		
		Location location = locationManager.getLastKnownLocation(provider);
		if (location != null)
			updateWithNewLocation(location);

		// Set the location listener 
		// time is in milliseconds
		// distance is in meters
		locationListener = new LocationListenerHelper(this);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minimumSeconds * 1000, minimumDistance, locationListener);
		//locationManager.requestLocationUpdates(provider, 10000, 0, locationListener);
		locationManager.addGpsStatusListener(locationListener);
	}

	// Stops the GPS Listeners
	public void stopLocationMonitoring()
	{
		Utilities.LogInfo("Stopping GPS managers");

		if (locationListener != null)
		{
			locationManager.removeUpdates(locationListener);
			locationManager.removeGpsStatusListener(locationListener);
		}

		Utilities.msgUser("Stopping GPS managers",getApplicationContext());
	}
	
	// This function creates a pop up box
	// which alerts the user about the selection they just made
	private void createAlert(String building)
	{
		Context context = MapActivity.this;
		String title = "confirm";
		String message = "You clicked on " + building + ". Do you want a Video tour to this building?";
		String choice2 = "No";
		String choice1 = "Yes";
		
		AlertDialog.Builder ad = new AlertDialog.Builder(context);
		ad.setTitle(title);
		ad.setMessage(message);
		
		// Yes
		ad.setPositiveButton(choice1, new OnClickListener()
		{
			public void onClick(DialogInterface dialog, int arg1)
			{
				Utilities.LogDebug("MapActivity-createAlert", "Yes is clicked");
				startVideoTour();
			}

		});
		
		// No
		ad.setNegativeButton(choice2, new OnClickListener()
		{
			public void onClick(DialogInterface dialog, int arg1)
			{
				// do nothing
			}

		});
		
		// Cancel
		ad.setCancelable(true);
		ad.setOnCancelListener(new OnCancelListener()
		{
			public void onCancel(DialogInterface dialog)
			{
				// do nothing
			}

		});
		
		ad.show();
		
	}

	// Part One of Video Tour
	// This function creates a direct video using only one video and one route
	public void startVideoTourDirectRoute() {
		SmartTourDBAdapter DB;
		DB =  new SmartTourDBAdapter(this);
		// Open Database
		DB.open();
		Cursor cursor;
		// TODO Auto-generated method stub
		Utilities.LogDebug("MapActivity-startVideoTourDirectRoute","User wants to start Video Tour");
		
		// Check if building is selected
		if ((buildingX > 0) && (buildingY > 0))
		{
			Utilities.LogDebug("MapActivity-startVideoTourDirectRoute","Building X and Y are postive");
			// Get information from database table
			cursor = DB.getAllSELocationItems();
			if (cursor.moveToFirst())
			{
				do
				{
					// Check information for the building for the tour
					int _id = cursor.getInt(cursor.getColumnIndex(SmartTourDBAdapter.KEY_ID));
					String _fileName = cursor.getString(cursor.getColumnIndex(SmartTourDBAdapter.KEY_FILE));
					Utilities.LogDebug("SR-startVideoTourDirectRoute", "Got::" + _id);
					Utilities.LogDebug("SR-startVideoTourDirectRoute", "Got::" + _fileName);
					int checkX = cursor.getInt(cursor.getColumnIndex(SmartTourDBAdapter.KEY_ENDING_LOCATION_X));
					int checkY = cursor.getInt(cursor.getColumnIndex(SmartTourDBAdapter.KEY_ENDING_LOCATION_Y));
					String testLocation = queryForBuilding(checkX,checkY);
					if (testLocation == currentBuildingName)
					{
						Utilities.LogDebug("SR-startVideoTourDirectRoute", "Ending location of video matches::" + testLocation);
						playVideo(_fileName);
						break;
					}
					
					
				}while(cursor.moveToNext());
				Utilities.LogDebug("SR-startVideoTourDirectRoute", "DONE");
			}
			else
			{
				Utilities.LogDebug("MapActivity-startVideoTourDirectRoute","DB is empty");
			}
			
			cursor.close(); 
		}
		else
			Utilities.LogWarning("MapActivity-startVideoTourDirectRoute: Building X and Y are negative");
		
	}
	
	// If its not in map view this function is called
	// This checks if there is a current location or
	// 2 buildings need to be slected
	private void processSelectionClick() {
		
		if (currentLocationSelectionView)
		{
			createAlert(currentBuildingName);
		}else if (buildingLocationSelectionView)
		{
			// If this is the first building save and go on
			if (firstBuildingSection == "")
			{
				firstBuildingSection = building_names[buildingSelected];
				Utilities.msgUser("Starting Location: " + firstBuildingSection , getApplicationContext());
			}else
			{
				createAlert(currentBuildingName); // Ask to start Tour
			}
				
		}
	}
	
	// Find starting location

	private int[] getCurrentXY() 
	{
		int[] XY = new int[2];
		if (currentLocationSelectionView)
		{
			// get current user location
			Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			XY = locationToXY(location);
		}else if(buildingLocationSelectionView)
		{
			Utilities.LogDebug("MapActivity-getCurrentXY","Building Index" + firstBuildingSection);
			// Get starting building location
			XY[0] = finder.buildingEntrances.get(firstBuildingSection);
			XY[1] = -1;
			firstBuildingSection = currentBuildingName;
		}
		
		return XY;
	}
	
	// Video tour with shortest route
	public void startVideoTour() {
		// Open Database
		SmartTourDBAdapter DB = new SmartTourDBAdapter(this);		
		DB.open();
		
		Cursor cursor;
		Cursor temp;
		long tempTime = 0;
		ArrayList<FilesToPlay> files = new ArrayList<FilesToPlay>();
		// TODO Auto-generated method stub
		Utilities.LogDebug("MapActivity-startVideoTour","User wants to start Video Tour");

		if ((buildingX > 0) && (buildingY > 0))
		{
			Utilities.LogDebug("MapActivity-startVideoTour","Building X and Y are postive");
			//Finding the current users postion
			int[] currentUserXY = getCurrentXY();
			int[] startingNode = new int[2];
			
			// GEt building location 
			if (currentUserXY[1] == -1)
			{
				startingNode[1] = currentUserXY[0];
				startingNode[0] = -1;
			}
			else // else users location is used for node
			{
				startingNode = finder.nearestNode(currentUserXY[0], currentUserXY[1]);
			}
			
			int nodeOfBuilding = finder.buildingEntrances.get(currentBuildingName);
			
			
			// Find shortest Path
			ArrayList<Node> shortestNodes = finder.findShortestPath(startingNode[1], nodeOfBuilding);
			
			// GEt all Video Nodes
			cursor = DB.getAllVideoNodes();
			
			// The for loop will go through each of the paths needed
			for (int i = 0; i < shortestNodes.size()-1; i++)
			{
				int currentNode = shortestNodes.get(i).name;
				int nextNode = shortestNodes.get(i+1).name;
				Utilities.LogDebug("SR-startVideoTour", "---currentNode:::" + currentNode);
				Utilities.LogDebug("SR-startVideoTour", "---nextNode:::" + nextNode);
				
				if (cursor.moveToFirst())
				{
					do
					{
						// gather information from DB
						int _id = cursor.getInt(cursor.getColumnIndex(SmartTourDBAdapter.KEY_ID));
						String db_fileName = cursor.getString(cursor.getColumnIndex(SmartTourDBAdapter.KEY_FILE));
						
						int db_startingNode = cursor.getInt(cursor.getColumnIndex(SmartTourDBAdapter.KEY_STARTING_NODE));
						int db_endingNode = cursor.getInt(cursor.getColumnIndex(SmartTourDBAdapter.KEY_ENDING_NODE));
						long db_startingTime = cursor.getLong(cursor.getColumnIndex(SmartTourDBAdapter.KEY_STARTING_TIME));
						long db_endingTime = cursor.getLong(cursor.getColumnIndex(SmartTourDBAdapter.KEY_ENDING_TIME));
						
						
						
						Utilities.LogDebug("SR-startVideoTour", "--CHECKING::" + _id);
						Utilities.LogDebug("SR-startVideoTour", "--CHECKING::" + db_fileName);
						
						// Find the current node + ending node match in database
						if ((db_startingNode == currentNode) && (db_endingNode == nextNode))
						{
							Utilities.LogDebug("SR-startVideoTour", "-Match Found for First Node:" + currentNode);
							Utilities.LogDebug("SR-startVideoTour", "-Match Found for 2nd Node:" + nextNode);
							
							// Find the starting time for the video it self
							Utilities.LogDebug("SR-startVideoTour", "Temp file Name: " + db_fileName);
							temp = DB.getAllSELocationItems();
							Utilities.LogDebug("SR-startVideoTour", "Temp Count: " + temp.getCount());
							
							// Find the starting time of the Video so it can be subtracted to get video length
							if (temp.moveToFirst())
							{
								do
								{
									String checkFileName = temp.getString(temp.getColumnIndex(SmartTourDBAdapter.KEY_FILE));
									Utilities.LogDebug("SR-startVideoTour", "DB FILE NAME: " + checkFileName + "::" + db_fileName);
									if (checkFileName.equals(db_fileName))
									{
										tempTime = temp.getLong(temp.getColumnIndex(SmartTourDBAdapter.KEY_STARTING_TIME));
										break;
									}									
								}while(temp.moveToNext());
							}
							
							Utilities.LogDebug("SR-startVideoTour", "Starting Time for the File: " + tempTime);
							
							// Set files to send to server
							db_fileName = db_fileName.replace("'","");
							FilesToPlay f = new FilesToPlay();
							f.fileName = db_fileName;
							f.startingTime = ((db_startingTime/1000) - (tempTime/1000));
							f.endingTime = ((db_endingTime/1000) - (tempTime/1000));
						//	Utilities.LogDebug("SR-startVideoTour", "---" + currentNode);
							//Utilities.LogDebug("SR-startVideoTour", "-File:" + files[i].fileName);
							//Utilities.LogDebug("SR-startVideoTour", "-Start Time (db) (temp) :" + db_startingTime + "::" + tempTime);
							//Utilities.LogDebug("SR-startVideoTour", "-Start Time (db) (temp) :" + db_endingTime + "::" + tempTime);
							//Utilities.LogDebug("SR-startVideoTour", "---" + nextNode);
							f.skip = false;
							Utilities.LogDebug("SR-startVideoTour", f.toString());
							files.add(f);
							break;
						}
						
					}while(cursor.moveToNext());
					Utilities.LogDebug("SR-startVideoTour", "DONE");
				}
				else
				{
					Utilities.LogDebug("MapActivity-startVideoTour","DB is empty");
				}

				
			}
			cursor.close();
			playVideo(files);
		}
		else
			Utilities.LogWarning("MapActivity-startVideoTour: Building X and Y are negative");
		DB.close();

	}
	
	// Set up data to be ready to send to server
	void playVideo(ArrayList<FilesToPlay> filesArray) 
	{
		Utilities.LogDebug("SR-playVideo", "Count: " + filesArray.size());
		String[] argsData = new String[(filesArray.size())*6];
		//int i;
		for (int i = 0; i < (filesArray.size()); i++)
		{			
			int startingNumber = (i * 6);
			if (i == 0) // first element
			{
				argsData[0] = "name[0]";
				argsData[1] = filesArray.get(i).fileName;
				argsData[2] = "startingTime[0]";
				argsData[3] = Long.toString(filesArray.get(i).startingTime);
				argsData[4] = "endingTime[0]";
				argsData[5] = Long.toString(filesArray.get(i).endingTime);
			}
			else // all other
			{
				argsData[startingNumber] = "name[" + i + "]";
				argsData[startingNumber + 1] = filesArray.get(i).fileName;
				argsData[startingNumber + 2] = "startingTime[" + i + "]";
				argsData[startingNumber + 3] = Long.toString(filesArray.get(i).startingTime);
				argsData[startingNumber + 4] = "endingTime[" + i + "]";
				argsData[startingNumber + 5] = Long.toString(filesArray.get(i).endingTime);
			}
		}
		
		// Debug
		for(int i=0; i<argsData.length; i+=2)
		{
		     Utilities.LogDebug(argsData[i] + ", " + argsData[i+1]);
		}
		
		playVideo(sendData("/ST/trimmer.php?", argsData));
	}

	// Once the server is ready play video file
	private void playVideo(String _fileName) 
	{
		FILE_NAME_FOR_PLAYBACK = _fileName;
		Intent playBack = new Intent(this, SmartViewer.class);
		startActivity(playBack);
	}
	
	
	// send the recive information from server
	private String sendData(String _serverFile, String[] data) 
	{

		Utilities.LogDebug(getClass().getSimpleName(), "send  task - start");
		//Utilities.LogDebug(getClass().getSimpleName(), "Data: " + data[0]);
		HttpParams p=new BasicHttpParams();
		p.setParameter("testing", (String) data[0]);

		String args = "";
		for (int i = 0; i < data.length; i = i + 2)
		{
			if (i ==0)
			{
				args = args + data[i] + "=" + data[i+1];
			}
			else{
				args = args + "&" + data[i] + "=" + data[i+1] ;
			}
		}
		Utilities.LogDebug(getClass().getSimpleName(), "Data: " + Utilities.IP_ADDRESS + _serverFile + args); 
		//Instantiate an HttpClient
		HttpClient client = new DefaultHttpClient(p);

		//Instantiate a GET HTTP method
		try {
			HttpResponse response=client.execute(new HttpGet(Utilities.IP_ADDRESS + _serverFile + args));
			InputStream is=response.getEntity().getContent();
			//You can convert inputstream to a string with: http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
			String output = convertStreamToString(is);
			Utilities.LogDebug("MapActivity - Server Response", output);
			Utilities.LogDebug(getClass().getSimpleName(), "send  task - end");
			return output;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			Utilities.LogError("MapActivity - Server Response", e);
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Utilities.LogError("MapActivity - Server Response", e);
			return null;
		}
	}
	
	private static String convertStreamToString(InputStream is)
	{
		/*
		 * To convert the InputStream to String we use the BufferedReader.readLine()
		 * method. We iterate until the BufferedReader return null which means
		 * there's no more data to read. Each line will appended to a StringBuilder
		 * and returned as String.
		 */
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	
	// Created a custom View to draw map
	class MyView extends View
	{
		public MyView(Context context)
		{
			super(context);
		}

		@Override
		protected void onDraw(Canvas canvas)
		{
			canvas.drawBitmap(adapt, 0, 0, paint);
			
			// -108 to compensate for png horizontal offset
			// -50 for canvas offset, -54 for png vertical offset
			// scrollX, scrollY compensate to lock image to the map
			canvas.drawBitmap(person, currentX - scrollX - 23, currentY - scrollY - 38 , paint);
			
			if (mapView == true) // show bubble
			{
				canvas.drawBitmap(bubble, buildingX - scrollX - 108, buildingY - scrollY - 54, paint);
				canvas.drawText(currentBuildingName, buildingX - scrollX - 97, buildingY - scrollY - 30, paint);
			}
		}
		
		// Update map
		public void redraw()
		{
			int[] temp = checkBounds(scrollX, scrollY, X_MAX - X_RES, Y_MAX - Y_RES);
			scrollX = temp[0];
			scrollY = temp[1];
			adapt = Bitmap.createBitmap(map, scrollX, scrollY, X_RES, Y_RES);
			//setTitle((scrollX) + ", " + (scrollY));
			invalidate();
		}

		// User needs to scoll the map
		public void handleScroll(float distX, float distY)
		{
			if(distX > 6.0)
			{
				if(scrollX < X_MAX - X_RES)  
				{
					scrollX += distX;
				}
			}
			else if(distX < -6.0)
			{
				if(scrollX >= 0)
				{
					scrollX += distX;
				}
			}
			if(distY > 6.0)
			{
				if(scrollY < Y_MAX - Y_RES)
				{
					scrollY += distY;
				}
			}
			else if(distY < -6.0)
			{
				if(scrollY >= 0)
				{
					scrollY += distY;
				}
			}
			redraw();
		}
	}
	
	// Class to hold file names and location
	class FilesToPlay
	{
		String fileName = "";
		long startingTime;
		long endingTime;
		boolean skip = true;
		
		FilesToPlay()
		{
			
		}
		
		public String toString()
		{
			String temp = "File Name: " + this.fileName + "\n Starting Time: " + this.startingTime + "\n Ending Time: " 
			+ this.endingTime;
			return temp;
		}
	}
}